'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Category extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      Category.hasMany(models.Course, {
        foreignKey: 'categoryId',
        as: 'courses'
      });
      // define association here
    }
  }
  Category.init({
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      unique:{
        msg: '名称不能重复'
      },
      validate: {
        notEmpty: {
          msg: '名称不能为空'
        },
        notNull: {
          msg: '名称不能为空'
        },
        len: {
          args: [1, 100],
          msg: '名称长度必须在1到100之间'
        }
      }
    },
    range: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notEmpty: { 
          msg: '范围不能为空'
        },
        notNull: {
          msg: '范围不能为空'
        },
        isInt: {
          msg: '范围必须是整数'
        },
        isPositive(value){
          if(value <= 0){
            throw new Error('范围必须大于0');
          }
        }
      }
    }
  }, {
    sequelize,
    modelName: 'Category',
  });
  return Category;
};